window.onload = () => {
  pageIdentify()
}
const pageIdentification = [
  {
    key: 'bugDetail',
    mark: [
      'work.ruiyunnet.com/biz/bug-view-',
    ],
  },
  {
    key: 'taskDetail',
    mark: [
      'work.ruiyunnet.com/biz/task-view-',
    ],
  }
]
function pageIdentify() {
  const href = location.href
  const page = pageIdentification.find(item => {
    const mark = item.mark
    const found = mark.find(m => href.indexOf(m) > -1)
    return found
  })
  if (page) {
    switch (page.key) {
      case 'bugDetail':
        bugMethods.listenBugResolve()
        break
      case 'taskDetail':
        taskMethods.listenTaskFinish()
        break
      default:
        break
    }
  }
}
const bugMethods = {
  // 监听bug解决的点击
  async listenBugResolve() {
    const btnIcon = await commonMethods.getDomAsync(() => {
      return document.querySelector('.icon-bug-resolve')
    })
    if (!btnIcon) return
    const btn = btnIcon.parentElement
    btn.onclick = () => {
      this.autoFillResolveForm()
    }
  },
  // 自动填入bug解决细节
  async autoFillResolveForm() {
    const doms = await autoFillCommon.getTableForm()
    if (!doms) return
    const {form, main} = doms
    const resolution = form.querySelector('#resolution')
    const resolution_chosen = form.querySelector('#resolution_chosen > a')
    commonMethods.selectValue(resolution, resolution_chosen, '已解决')
    const resolvedBuild = form.querySelector('#resolvedBuild')
    const resolvedBuild_chosen = form.querySelector('#resolvedBuild_chosen > a')
    commonMethods.selectValue(resolvedBuild, resolvedBuild_chosen, '主干')
    const assignedTo = form.querySelector('#assignedTo')
    const assignedTo_chosen = form.querySelector('#assignedTo_chosen > a')
    commonMethods.selectValue(assignedTo, assignedTo_chosen, 'L:李敏芳')
    autoFillCommon.fillComment(form)
    autoFillCommon.saveListen(form, main)
  }
}
const taskMethods = {
  async listenTaskFinish() {
    const taskIcon = await commonMethods.getDomAsync(() => {
      return document.querySelector('.icon-task-finish')
    })
    if (!taskIcon) return
    const btn = taskIcon.parentElement
    btn.onclick = () => {
      this.autoFillFinishForm()
    }
  },
  async autoFillFinishForm() {
    const doms = await autoFillCommon.getTableForm()
    if (!doms) return
    const {form, main} = doms
    const assignedTo = form.querySelector('#assignedTo')
    const assignedTo_chosen = form.querySelector('#assignedTo_chosen > a')
    commonMethods.selectValue(assignedTo, assignedTo_chosen, 'Z:张宝明')
    autoFillCommon.fillComment(form)
    autoFillCommon.saveListen(form, main)
  }
}
const autoFillCommon = {
  getTableForm() {
    return commonMethods.getDomAsync(() => {
      const frame = document.querySelector('#iframe-triggerModal')
      try {
        const doc = frame.contentWindow.document
        const main = doc.querySelector('#mainContent')
        const form = main.querySelector('.table-form')
        if (form) {
          return {form, main}
        }
      } catch(err) {}
      return null
    }).then(result => {
      if (!result) console.log('查找不到表单DOM')
      return result
    })
  },
  fillComment(form) {
    const editIframe = form.querySelector('.ke-edit-iframe')
    const doc = editIframe.contentWindow.document
    const content = doc.querySelector('.article-content')
    content.innerText = 'SVN#'
    const placeholder = form.querySelector('.kindeditor-ph')
    placeholder.style.display = 'none'
    const container = form.querySelector('.ke-container')
    container.classList.add('focus')
  },
  autoCopyTitle(main) {
    const title = main.querySelector('.main-header').innerText
    commonMethods.copyText(title)
  },
  saveListen(form, main) {
    const submitBtn = form.querySelector('#submit')
    submitBtn.onclick = () => {
      autoFillCommon.autoCopyTitle(main)
    }
  }
}
const commonMethods = {
  // 设置选择值
  selectValue(selection, chosen, value) {
    const options = selection.querySelectorAll('option');
    for (let i = 0; i < options.length; i++) {
      const opt = options[i]
      const text = opt.text
      if (text === value || text.includes(value)) {
        const chosenText = chosen.querySelector('span')
        selection.value = opt.value // 直接设置值
        chosenText.innerText = text; // 设置选中文本
        chosen.classList.remove('chosen-default')
        chosen.classList.add('chosen-single-with-deselect')
        break
      }
    }
  },
  // 获取执行dom查找条件，异步获取，定时查询
  getDomAsync(selectFn, maxCounter) {
    if (!maxCounter) maxCounter = 20; // 默认20次查询 6秒
    return new Promise(resolve => {
      let counter = 0; // 防止无限循环
      const timer = setInterval(() => {
        if (counter > maxCounter) {
          resolve(null);
          clearInterval(timer);
        }
        const dom = selectFn();
        if (dom) {
          resolve(dom);
          clearInterval(timer);
        }
        counter++;
      }, 300);
    })
  },
  /**
    * @param {String} text 需要复制的内容
    * @return {Boolean} 复制成功:true或者复制失败:false  执行完函数后，按ctrl + v试试
  */
  copyText(text) {
    const textareaEl = document.createElement('textarea')
    textareaEl.setAttribute('readonly', 'readonly') // 防止手机上弹出软键盘
    textareaEl.value = text
    document.body.appendChild(textareaEl)
    textareaEl.select()
    const res = document.execCommand('copy')
    document.body.removeChild(textareaEl)
    console.log('复制结果：', res)
    return res
  }
}